#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import pandas as pd
import numpy as np
import json

print("开始学生社交媒体数据深度分析...")

# 加载数据
df = pd.read_csv('学生社交媒体与人际关系数据集/学生社交媒体与人际关系数据集.csv')
print(f"数据加载成功！形状: {df.shape}")

print("\n=== 基本信息分析 ===")
print("数据集包含以下字段:")
for i, col in enumerate(df.columns, 1):
    print(f"{i}. {col} ({df[col].dtype})")

print(f"\n数据集大小: {df.shape[0]:,} 个学生样本")
print(f"缺失值检查: {df.isnull().sum().sum()} 个缺失值")

print("\n=== 关键发现 ===")

# 基本统计
avg_usage = df['Avg_Daily_Usage_Hours'].mean()
avg_mental_health = df['Mental_Health_Score'].mean()
avg_addiction = df['Addicted_Score'].mean()
avg_sleep = df['Sleep_Hours_Per_Night'].mean()
academic_affected_pct = (df['Affects_Academic_Performance'] == 'Yes').mean() * 100

print(f"1. 平均每日社交媒体使用时间: {avg_usage:.1f} 小时")
print(f"2. 平均心理健康评分: {avg_mental_health:.1f}/10")
print(f"3. 平均成瘾评分: {avg_addiction:.1f}/10")
print(f"4. 平均睡眠时间: {avg_sleep:.1f} 小时/晚")
print(f"5. 认为影响学术表现的学生比例: {academic_affected_pct:.1f}%")

print("\n=== 平台使用分析 ===")
platform_dist = df['Most_Used_Platform'].value_counts()
print("最受欢迎的社交媒体平台:")
for i, (platform, count) in enumerate(platform_dist.head().items(), 1):
    pct = count / len(df) * 100
    print(f"{i}. {platform}: {count:,} 用户 ({pct:.1f}%)")

print("\n=== 人口统计分析 ===")
print("性别分布:")
gender_dist = df['Gender'].value_counts()
for gender, count in gender_dist.items():
    pct = count / len(df) * 100
    print(f"  {gender}: {count:,} ({pct:.1f}%)")

print("\n学历分布:")
academic_dist = df['Academic_Level'].value_counts()
for level, count in academic_dist.items():
    pct = count / len(df) * 100
    print(f"  {level}: {count:,} ({pct:.1f}%)")

print("\n=== 关键相关性分析 ===")
# 数值变量相关性
numeric_cols = ['Avg_Daily_Usage_Hours', 'Mental_Health_Score', 'Addicted_Score', 'Sleep_Hours_Per_Night']
correlations = df[numeric_cols].corr()

print("重要相关关系:")
usage_mental_corr = df['Avg_Daily_Usage_Hours'].corr(df['Mental_Health_Score'])
usage_addiction_corr = df['Avg_Daily_Usage_Hours'].corr(df['Addicted_Score'])
sleep_mental_corr = df['Sleep_Hours_Per_Night'].corr(df['Mental_Health_Score'])
addiction_mental_corr = df['Addicted_Score'].corr(df['Mental_Health_Score'])

print(f"1. 使用时间 vs 心理健康: {usage_mental_corr:.3f}")
print(f"2. 使用时间 vs 成瘾程度: {usage_addiction_corr:.3f}")
print(f"3. 睡眠时间 vs 心理健康: {sleep_mental_corr:.3f}")
print(f"4. 成瘾程度 vs 心理健康: {addiction_mental_corr:.3f}")

print("\n=== 深度洞察分析 ===")

# 高风险群体分析
high_usage_threshold = 6
high_addiction_threshold = 8
low_mental_health_threshold = 5

high_usage_count = (df['Avg_Daily_Usage_Hours'] > high_usage_threshold).sum()
high_addiction_count = (df['Addicted_Score'] >= high_addiction_threshold).sum()
low_mental_health_count = (df['Mental_Health_Score'] <= low_mental_health_threshold).sum()

print(f"高风险群体识别:")
print(f"1. 高使用时间群体 (>{high_usage_threshold}h/天): {high_usage_count:,} 人 ({high_usage_count/len(df)*100:.1f}%)")
print(f"2. 高成瘾风险群体 (≥{high_addiction_threshold}分): {high_addiction_count:,} 人 ({high_addiction_count/len(df)*100:.1f}%)")
print(f"3. 低心理健康群体 (≤{low_mental_health_threshold}分): {low_mental_health_count:,} 人 ({low_mental_health_count/len(df)*100:.1f}%)")

# 平台与成瘾的关系
print(f"\n各平台平均成瘾评分:")
platform_addiction = df.groupby('Most_Used_Platform')['Addicted_Score'].mean().sort_values(ascending=False)
for platform, score in platform_addiction.items():
    print(f"  {platform}: {score:.2f}/10")

# 学术影响分析
print(f"\n学术表现影响分析:")
affected_avg_usage = df[df['Affects_Academic_Performance'] == 'Yes']['Avg_Daily_Usage_Hours'].mean()
not_affected_avg_usage = df[df['Affects_Academic_Performance'] == 'No']['Avg_Daily_Usage_Hours'].mean()

print(f"认为影响学术表现的学生平均使用时间: {affected_avg_usage:.2f} 小时")
print(f"认为不影响学术表现的学生平均使用时间: {not_affected_avg_usage:.2f} 小时")
print(f"差异: {affected_avg_usage - not_affected_avg_usage:.2f} 小时")

# 关系状态分析
print(f"\n人际关系分析:")
relationship_dist = df['Relationship_Status'].value_counts()
for status, count in relationship_dist.items():
    pct = count / len(df) * 100
    avg_conflicts = df[df['Relationship_Status'] == status]['Conflicts_Over_Social_Media'].mean()
    print(f"  {status}: {count:,} ({pct:.1f}%) - 平均冲突次数: {avg_conflicts:.2f}")

print("\n=== 关键结论与建议 ===")

conclusions = []

if avg_usage > 4:
    conclusions.append(f"学生社交媒体使用时间较高（平均{avg_usage:.1f}小时），需要关注时间管理")

if academic_affected_pct > 50:
    conclusions.append(f"超过一半学生({academic_affected_pct:.1f}%)认为社交媒体影响学术表现")

if avg_mental_health < 7:
    conclusions.append(f"学生心理健康水平需要关注（平均{avg_mental_health:.1f}/10）")

if high_addiction_count/len(df) > 0.2:
    conclusions.append(f"约{high_addiction_count/len(df)*100:.1f}%的学生有较高成瘾风险")

if avg_sleep < 7:
    conclusions.append(f"学生睡眠时间不足（平均{avg_sleep:.1f}小时），可能与社交媒体使用相关")

for i, conclusion in enumerate(conclusions, 1):
    print(f"{i}. {conclusion}")

# 保存分析结果
results = {
    'basic_stats': {
        'total_students': int(df.shape[0]),
        'avg_daily_usage': float(avg_usage),
        'avg_mental_health': float(avg_mental_health),
        'avg_addiction_score': float(avg_addiction),
        'avg_sleep_hours': float(avg_sleep),
        'academic_affected_percentage': float(academic_affected_pct)
    },
    'platform_analysis': platform_dist.to_dict(),
    'demographics': {
        'gender': gender_dist.to_dict(),
        'academic_level': academic_dist.to_dict()
    },
    'correlations': {
        'usage_mental_health': float(usage_mental_corr),
        'usage_addiction': float(usage_addiction_corr),
        'sleep_mental_health': float(sleep_mental_corr),
        'addiction_mental_health': float(addiction_mental_corr)
    },
    'risk_groups': {
        'high_usage_count': int(high_usage_count),
        'high_addiction_count': int(high_addiction_count),
        'low_mental_health_count': int(low_mental_health_count)
    },
    'platform_addiction_scores': platform_addiction.to_dict(),
    'relationship_analysis': relationship_dist.to_dict(),
    'conclusions': conclusions
}

with open('analysis_results.json', 'w', encoding='utf-8') as f:
    json.dump(results, f, ensure_ascii=False, indent=2)

print(f"\n分析完成！结果已保存到 analysis_results.json")
print("=" * 60)
